package impl

import (
	pConstants "anubis-framework/pkg/constants"
	pDomain "anubis-framework/pkg/domain"
	"anubis-framework/pkg/util"
	"github.com/gin-gonic/gin"
	"net/http"
	"newton/internal/dto"
	"newton/internal/model"
	"newton/internal/service"
	"newton/internal/service/impl"
)

type UserController struct {
	_userServiceImpl service.UserService
}

// 获取UserController
func GetUserController() *UserController {
	return &UserController{impl.GetUserServiceImpl()}
}

// 登录
func (_userController *UserController) Login(c *gin.Context) {
	var user *model.User = &model.User{}
	c.BindJSON(user)

	var apiResult *pDomain.ApiResult = &pDomain.ApiResult{}
	var serviceResult *pDomain.ServiceResult = _userController._userServiceImpl.Login(user)
	if serviceResult.Success == true {
		var _user *model.User = serviceResult.Result.(*model.User)

		var userInfoDto *dto.UserInfoDto = &dto.UserInfoDto{}
		userInfoDto.Id = _user.Id
		userInfoDto.Username = _user.Username
		var token = util.CreateToken()
		userInfoDto.Token = token

		apiResult.Code = pConstants.LoginSuccessCode
		apiResult.Message = pConstants.LoginSuccessMessage
		apiResult.Success = true
		apiResult.Result = userInfoDto
	} else {
		apiResult.Code = pConstants.LoginFailCode
		apiResult.Message = pConstants.LoginFailMessage
		apiResult.Success = false
	}

	c.JSON(http.StatusOK, *apiResult)
	return
}
